package com.wswy.wzcx.ui.weather

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.support.v4.content.ContextCompat
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.format.DateFormat
import android.text.style.RelativeSizeSpan
import android.text.style.SuperscriptSpan
import android.view.View
import com.che.libcommon.utils.ToastUtils
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.tencent.bugly.crashreport.CrashReport
import com.wswy.wzcx.R
import com.wswy.wzcx.model.weather.WeatherData
import com.wswy.wzcx.module.base.CBaseActivity
import com.wswy.wzcx.module.weather.WeatherUtils
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.utils.FrescoUtils
import com.wswy.wzcx.utils.LunarCalender
import com.wswy.wzcx.utils.UiUtils
import kotlinx.android.synthetic.main.activity_proxy_screen_weather.*
import java.io.File
import java.io.FileOutputStream
import java.util.*


class ProxyScreenActivity : CBaseActivity() {

    companion object {
        private const val TAKE_TIMEOUT = 2000L

        private const val MSG_TAKE_TIMEOUT = 12

        private const val TAG = "ProxyScreenActivity"
    }

    private val handler = Handler {

        if (it.what == MSG_TAKE_TIMEOUT){
            takeScreenShot()
        }

        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_proxy_screen_weather)

        UiUtils.setStatusBarLight(this, false)


        intent?.getParcelableExtra<WeatherData?>(Constants.EXTRA_DATA)?.run {
            bindData(this)
        }

    }


    private fun takeScreenShot(){
        handler.removeMessages(MSG_TAKE_TIMEOUT)

        img_fg.postOnAnimation(imageCheckRunnable)
    }

    private var checkRepeat = 1

    private val imageCheckRunnable = object :Runnable {
        override fun run() {


            if ( checkRepeat < 10 && img_fg.drawable != null){
                //takeScreenShotOfView(root_content)

                checkRepeat = 10
                img_fg.postOnAnimation(this)

            }else{

                if (checkRepeat < 10){
                    img_fg.postOnAnimation(this)
                    checkRepeat++
                }else{
                    takeScreenShotOfView(root_content)
                }
            }
        }
    }

    private fun bindData(weatherData: WeatherData){

        weatherData.liveWeather?.run {

            tv_city.text = city

            val now = Date()
            tv_tips.text = WeatherUtils.getWeatherTips(weather)

            handler.sendEmptyMessageDelayed(MSG_TAKE_TIMEOUT,TAKE_TIMEOUT)

            ll_content.background = ProxyDrawable(ContextCompat.getDrawable(applicationContext,WeatherUtils.getWeatherBg(weather)))


            UiUtils.addOnGlobalLayoutListener(img_fg){
                ImageRequestBuilder.newBuilderWithSource(WeatherUtils.getWeatherFg(weather))
                        .setPostprocessor(ProxyWeatherBgProcessor(it.width,it.height))
                        .build().run {

                            FrescoUtils.loadBitmap(this)
                                    .subscribe { t1, t2 ->

                                t1?.orNull()?.let {
                                    img_fg.setImageBitmap(it)
                                }

                                t2?.printStackTrace()
                                takeScreenShot()
                            }

//                            img_fg.controller = Fresco.newDraweeControllerBuilder()
//                                    .setImageRequest(this)
//                                    .setControllerListener(object :BaseControllerListener<ImageInfo>(){
//                                        override fun onFailure(id: String?, throwable: Throwable?) {
//                                            super.onFailure(id, throwable)
//                                            Log.e(TAG, " --> onFailure");
//                                            takeScreenShot()
//                                        }
//
//                                        override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
//                                            super.onFinalImageSet(id, imageInfo, animatable)
//
//                                            takeScreenShot()
//                                            Log.e(TAG, " --> onFinalImageSet ${imageInfo?.width}  ${imageInfo?.height}");
//
//                                        }
//
//                                    })
//                                    .setOldController(img_fg.controller)
//                                    .build()

                        }
            }

            showDate(if (now.after(reportTime)) now else reportTime,weather)

            tv_humidity.text = "${humidity}%"
            tv_wind.text = "${windPower}级"
            tv_wind_direction.text = "${windDirection}风"
//
            tv_wash_car.text = weatherData.washCarDesc

            SpannableStringBuilder().run {

                append(temperature)

                append(SpannableString(getString(R.string.temperature_symbol)).apply {
                    setSpan(SuperscriptSpan(),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                    setSpan(RelativeSizeSpan(0.26667f),0,length,SpannableString.SPAN_INCLUSIVE_EXCLUSIVE)
                })

                tv_temperature.text =this
            }


        }
    }

    private fun showDate(date: Date,weather:String?){
        LunarCalender().run {

            setDate(date)

            tv_yang_time.text = "${DateFormat.format("MM月dd日",date)}  $week  $weather"

            tv_nong_time.text = "${chineseMonth}${chineseDay} ${chineseYear}年"

        }
    }


    override fun autoHackStatusBar(): Boolean {
        return false
    }

    private fun takeScreenShotOfView(view:View){
        view.run {

            val path:File? =  try {
                 saveScreenshotToPicturesFolder(save(this),"weather_share")
            }catch (e:Throwable){
                e.printStackTrace()
                ToastUtils.showText("保存截图失败")
                CrashReport.postCatchedException(e)
                null
            }

            //Log.e(TAG, " -->out path $path ")

            if (path?.exists() == true) {
                setResult(Activity.RESULT_OK, Intent().apply {
                    putExtra(Constants.EXTRA_DATA, path.absolutePath)
                })
            }
            finish()

        }
    }


    private fun save(view: View):Bitmap?{

        var bitmap : Bitmap? = null

        val ret = view.runCatching {
            isDrawingCacheEnabled = true
            buildDrawingCache(true)

            drawingCache?.let {
                bitmap = Bitmap.createBitmap(it)
            }
            isDrawingCacheEnabled = false
        }

        ret.exceptionOrNull()?.printStackTrace()

        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(view.width,view.height,Bitmap.Config.ARGB_8888)

            val canvas = Canvas(bitmap)

            view.draw(canvas)

        }

        return bitmap

    }


    @Throws(Exception::class)
    fun saveScreenshotToPicturesFolder( image: Bitmap?, filename: String): File? {
        val bitmapFile = getOutputMediaFile(filename)
                ?: throw NullPointerException("Error creating media file, check storage permissions!")

        image?:return null

        FileOutputStream(bitmapFile).use {
            image.compress(Bitmap.CompressFormat.JPEG, 90, it)
        }

        return bitmapFile
    }

    private fun getOutputMediaFile(filename: String): File? {

        val dir =  getExternalFilesDir(Environment.DIRECTORY_PICTURES)?:Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

        return dir?.let {
            if (!it.exists()){
                it.mkdirs()
            }

            return  File(it, "$filename.jpg")

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(MSG_TAKE_TIMEOUT)
    }

}